<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Support\Facades\Hash;

use Illuminate\Http\Request;

class LoginSignController extends Controller
{
    //
    public function login(Request $request)
    {
        $data = $request->all();
        $user = User::where('loginname', $data['loginname'])->first();
        if (!$user) {
            return response()->json([
                'code' => '201',
                'msg' => '用户名或密码错误',
            ], 201);
        }
        if (!Hash::check($data['password'], $user->password)) {
            return response()->json([
                'code' => '201',
                'msg' => '用户名或密码错误',
            ], 201);
        }
        return response()->json([
            'code' => '200',
            'msg' => '成功',
            'data' => $user
        ], 200);
    }
    public function sign(Request $request)
    {
        $data = $request->all();

        $userExists = User::where('loginname', $data['loginname'])->exists();
        if ($userExists) {
            return response()->json(['code' => '201', 'msg' => '注册失败，用户名已经存在']);
        }
        $user = new User;
        $user->loginname = $data['loginname'];
        $user->password = Hash::make($data['password']);
        $user->save();
        return response()->json(['code' => '200', 'msg' => '注册成功']);
    }
    public function reset(Request $request)
    {
        $user = User::where('loginname', $request->input('loginname'))->first();
        if (!Hash::check($request->input('password'), $user->password)) {
            return response()->json([
                'code' => 201,
                'msg' => '旧密码错误'
            ], 201);
        }
        if (!preg_match("/^.{8,16}$/", $request->input('newPassword'))) {
            return response()->json([
                'code' => 201,
                'msg' => '新密码长度必须在8到16个字符之间'
            ], 201);
        }
        User::where('loginname', '=', $request->input('loginname'))->update(['password' => Hash::make($request->input('newPassword'))]);
        return response()->json([
            'code' => 200,
            'msg' => '修改成功'
        ], 200);
    }
}
